package org.cwnuit.train.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell; 
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@SuppressWarnings("all")
public class CreateExcel {

	/**
	 * 
	 * 解决中文乱码问题
	 */

	public static String getUnicode(String toEncoded, String encoding) {
		String retString = "";
		if (toEncoded.equals("") || toEncoded.trim().equals("")) {
			return toEncoded;
		}
		try {
			byte[] b = toEncoded.getBytes(encoding);
			sun.io.ByteToCharConverter convertor = sun.io.ByteToCharConverter
					.getConverter(encoding);
			char[] c = convertor.convertAll(b);
			for (int i = 0; i < c.length; i++) {
				retString += String.valueOf(c[i]);
			}
		} catch (java.io.UnsupportedEncodingException usee) {
			System.out.println("不支持" + encoding + "编码方式");
			usee.printStackTrace();
		} catch (sun.io.MalformedInputException mfie) {
			System.out.println("输入参数无效!!!");
			mfie.printStackTrace();
		}
		return retString;
	}

	/**
	 * 写入EXCEL
	 */

	public String createExcel(String path,String file,List list) {
		String outputPath = path;
		String outputFile = file;
		try {
			// 如果outputPath不存在,则创建路径
			if (!new java.io.File(outputPath).isDirectory()) {
				new java.io.File(outputPath).mkdirs();
			}
			File objFile = new File(outputFile);
			HSSFWorkbook workbook = null;
			HSSFSheet sheet = null;
			String table_name = "导出数据";
			// 创建文件
			workbook = new HSSFWorkbook();
			sheet = workbook.createSheet(table_name);
			FileOutputStream fOut = new FileOutputStream(outputFile);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();

			workbook = new HSSFWorkbook(new FileInputStream(outputFile));
			sheet = workbook.getSheet(table_name);
			for (int i = 0; i < list.size(); i++) {
				List lt = (ArrayList) list.get(i);
				for (int j = 0; j < lt.size(); j++) {
					HSSFRow row = sheet.createRow((short) i);
					HSSFCell cell = row.createCell((short) j);
					cell.setCellType(HSSFCell.CELL_TYPE_STRING);
					cell.setEncoding(HSSFCell.ENCODING_UTF_16);
					String text;
					try {
						text = lt.get(j).toString();
					} catch (Exception e) {
						text = "";
					}
					text = getUnicode(text, "gb2312");
					cell.setCellValue(text);
					FileOutputStream fOut1 = new FileOutputStream(outputFile);
					workbook.write(fOut1);
					fOut.flush();
					fOut.close();
				}
			}
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "导出失败！";
		}
	}
}
